package control

import (
	"fmt"
    "net/http"
	"crypto/md5"
	"encoding/hex"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"mysql"
	"time"
)

type JwtLogin struct {
	Email string
	Pwd   string
	jwt.StandardClaims
}
//md5 the mima
func MD5(v string)string{
	d := []byte(v)
	m := md5.New()
	m.Write(d)
	return hex.EncodeToString(m.Sum(nil))
}
//func to deal client sign in
func SignIn(c *gin.Context) {
	email := c.PostForm("email")
	pwd := c.PostForm("password")
	pwd=MD5(pwd);
	fmt.Printf("email %s,passwd %s\n",email,pwd)
	var user mysql.User
	user.Email = email
	user.Pwd = pwd
	flag, _ := mysql.SqlSignIn(&user)
	key1 := []byte("chenxuan")
	temp := JwtLogin{
		Email: email,
		Pwd:   pwd,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 60,
			ExpiresAt: time.Now().Unix() + 60*60*60,
			Issuer:    "chenxuan",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, temp)
	str, err := token.SignedString(key1)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"error": err,
		})
	}
	if flag == true {
		cookle:=http.Cookie{
			Name:"key",
			Value:str,
			MaxAge:60,
		}
		http.SetCookie(c.Writer,&cookle);
		c.JSON(http.StatusOK, gin.H{
			"name": email,
			"val":  pwd,
			"str":  str,
		})
	} else {
		c.JSON(http.StatusNotFound, gin.H{
			"status": "wrong",
		})
	}
}

// loginIn set zhuche
func Enroll(c *gin.Context) {
	email := c.PostForm("email")
	pwd := c.PostForm("password")
	pwd=MD5(pwd);
	flag,err:=mysql.SqlFind(email);
	if err!=nil||flag{
		c.JSON(http.StatusOK,gin.H{
			"status":err,
		})
		return;
	}
	key1 := []byte("chenxuan")
	temp := JwtLogin{
		Email: email,
		Pwd:   pwd,
		StandardClaims: jwt.StandardClaims{
			NotBefore: time.Now().Unix() - 60,
			ExpiresAt: time.Now().Unix() + 60,
			Issuer:    "chenxuan",
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, temp)
	str, err := token.SignedString(key1)
	if err != nil {
		//    panic(err);
		fmt.Printf("error:%T,%s", key1, err)
	}
	msg := mysql.User{
		Email:  email,
		Pwd:    pwd,
		Status: 0,
		Permission: email=="root",
	}
	mysql.SqlCreate(&msg)
	var http1 string = "http://125.73.58.176:5206/sure/"
	http1 += str
	//sendTo:=[]string{
	//  "1607772321@qq.com",
	//}
	//SendMail(sendTo,"ok",http)
	c.JSON(http.StatusOK, gin.H{
		"email": email,
		"pwd":   pwd,
		"http":  http1,
	})
}

//function to change password
func PwdChange(c *gin.Context) {
	cookie,err:=c.Request.Cookie("key");
	if err!=nil||cookie.Value==""{
		c.JSON(http.StatusOK,gin.H{
			"wrong":err,
			"status": "please sign first",
		})
		return;
	}
	key:=cookie.Value;
	newPwd := c.PostForm("password")
	newPwd=MD5(newPwd);
	token, err := jwt.ParseWithClaims(key, &JwtLogin{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("chenxuan"), nil
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"wrong": err,
		})
		return
	}
	temp := mysql.User{
		Email:  token.Claims.(*JwtLogin).Email,
		Pwd:    newPwd,
		Status: 2,
		Permission:false,
	}
	fmt.Printf("email:%s\n", temp.Email)
	mysql.SqlChange(&temp)
	cookle:=http.Cookie{
		Name:"key",
		Value:"",
		MaxAge:-1,
	}
	http.SetCookie(c.Writer,&cookle);
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
	})
}

//deal http of jwt key
func DealSure(c *gin.Context) {
	key := c.Param("key")
	token, err := jwt.ParseWithClaims(key, &JwtLogin{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("chenxuan"), nil
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"wrong": err,
		})
		return
	}
	temp := mysql.User{
		Email:  token.Claims.(*JwtLogin).Email,
		Pwd:    token.Claims.(*JwtLogin).Pwd,
		Status: 2,
		Permission: false,
	}
	fmt.Printf("email:%s pass:%s\n", temp.Email,temp.Pwd)
	mysql.SqlChange(&temp)
	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
	})
}
 
//get all list
func RootGet(c *gin.Context){
	cookie,err:=c.Request.Cookie("key");
	if err!=nil||cookie.Value==""{
		c.JSON(http.StatusOK,gin.H{
			"wrong":"you are not root",
		})
		return;
	}
	key:=cookie.Value;
	token, err := jwt.ParseWithClaims(key, &JwtLogin{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("chenxuan"), nil
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"wrong": err,
		})
		return
	}
	temp:=token.Claims.(*JwtLogin).Email;
	flag,err:=mysql.SqlJudge(temp);
	if err!=nil||flag==false{
		c.JSON(http.StatusOK,gin.H{
			"error":"youare not root",
		})
		return;
	}
	users,num,err:=mysql.SqlGetALL();
	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"error":err,
		})
	}else{
		c.JSON(http.StatusOK,gin.H{
			"arr":users,
			"len":num,
		})
	}
}

// delete client
func RootDelete(c *gin.Context){
	email := c.PostForm("email")
	cookie,err:=c.Request.Cookie("key");
	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"wrong":err,
		})
		return
	}
	key:=cookie.Value;
	token, err := jwt.ParseWithClaims(key, &JwtLogin{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("chenxuan"), nil
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"wrong": err,
		})
		return
	}
	temp:=token.Claims.(*JwtLogin).Email;
	flag,err:=mysql.SqlJudge(temp);
	if err!=nil||flag==false{
		c.JSON(http.StatusOK,gin.H{
			"error":"you are not root",
		})
	}
	flag,err=mysql.SqlDelete(email);
	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"error":err,
			"email":email,
		})
	}
	c.JSON(http.StatusOK,gin.H{
		"status":"ok",
	})
}
//get status
func GetStatus(c *gin.Context){
	cookie,err:=c.Request.Cookie("key");
	if err!=nil{
		c.JSON(http.StatusOK,gin.H{
			"status":"you are not sign",
		})
		return
	}
	key:=cookie.Value;
	_, err = jwt.ParseWithClaims(key, &JwtLogin{}, func(token *jwt.Token) (interface{}, error) {
		return []byte("chenxuan"), nil
	})
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"status":"your jwt is over time",
		})
		return
	}
	c.JSON(http.StatusOK,gin.H{
		"sttaus":"you are login in",
	})
	
}
